<?

	class Controller_Login extends Controller_Base {

		function index ($args) {
//	 		$sesid = ($_COOKIE['sesid']) ? ($_COOKIE['sesid']) : ($_GET['sesid']);

			$admin = new Model_Admin_User();
			
			if($admin->is_logged())
				return array (status 	=> 302,	location	=> '/admin/');

//			$user = $admin->find(array(id => 11));

		 	$sigs = array(
		 			'user_name'		=> array('type' => 'string','function'=>array('addslashes'),'required' =>1),
		 			'password'		=> array('type' => 'string','function'=>array('addslashes'),'required' =>1),
		 			'redirect'		=> array('type' => 'string','function'=>array('addslashes')),
					// action
		 			'login'			=> array('type' => 'bool','required' =>1),
			);			

 			// check input params
			sanitize_vars(
				$_GET,  // variable
				array(	 // sigs 
					'return'	=> array('type' => 'string','function'=>array('addslashes'))
				), 
				null 		 // redirect
			);
	 	 	 		
	 		if($_POST['login']) {
 		
				// try to login
//	 			$sesid = $this->registry['session']->createSession(array(
//	 					user_name 	=> $_POST['user_name'],
//	 					password	=> $_POST['password'],
//	 			));
				
				try {
					$sesid = $admin->login($_POST['user_name'],$_POST['password']);
				} catch ( UserException $e ) {
					error_log("login error: ".$e->getMessage());
				}

				if($sesid) {
					
					$location = $_POST['redirect'] 
						? $_POST['redirect'] 
						: '/admin/';

//					error_log("Location: $location");
	 				
	 				$redirect = new Redirect($location);
	 				
	 				$redirect->setCookie(
						array( // session id
							name => 'SID',
							value => $sesid,
							time	=> time()+3600,
							path  =>  '/admin'
						)
					);
	 				
	 				return $redirect;
	 				
				} else 
	 				return new Redirect('/admin/');
	 				
	 		} else {

				// show login form
				$template = new Template('admin/login.tmpl');
	
				$template->setArgs(
					array(
						'title' 	=> 'авторизация',
						'uri' 		=> $_GET['return'],
					)
				);
	
				return $template;

	 		}
			
	 	}
	} 
?>